<template>
  <div class="tabs">
    <el-tabs v-model="activeName" @tab-click="tabClick">
      <el-tab-pane label="企业信息" name="info" v-if="$verifyPerms('ZEnterpriseInformation')">
          <tab-info ref="info" :infoData="infoData"></tab-info>
        </el-tab-pane>
      <el-tab-pane label="组织岗位管理" name="station" v-if="$verifyPerms('ZOrganizationPosition')">
        <tab-station ref="station" :infoData="infoData"></tab-station>
      </el-tab-pane>
      <el-tab-pane label="组织人员管理" name="personnel" v-if="$verifyPerms('ZOrganizationPersonnel')">
        <tab-personnel ref="personnel" :infoData="infoData"></tab-personnel>
      </el-tab-pane>
      <el-tab-pane label="菜单管理" name="menu" v-if="$verifyPerms('ZMenuManagement')">
        <tab-menu ref="menu" :infoData="infoData"></tab-menu>
      </el-tab-pane>
      <el-tab-pane label="操作日志" name="operation" v-if="$verifyPerms('ZOperationLog')">
        <tab-log ref="operation" :infoData="infoData"></tab-log>
      </el-tab-pane>
      <el-tab-pane label="离职管理" name="dimission" v-if="$verifyPerms('ZLeaveManagement')">
        <tab-dimission ref="dimission" :infoData="infoData"></tab-dimission>
      </el-tab-pane>
      <el-tab-pane label="技能标签" name="tag" v-if="$verifyPerms('ZSkillManagement')">
        <tab-tag ref="tag" :infoData="infoData"></tab-tag>
      </el-tab-pane>
    </el-tabs>

    <!-- 按钮组 -->
    <div class="btn-box">
      <el-button type="primary" size="mini" v-if="activeName == 'station'" @click="addGroup">新增组织</el-button>
      <el-button type="primary" size="mini" v-if="activeName == 'menu'" @click="showViewMenuDialog">预览</el-button>
      <el-button type="primary" size="mini" v-if="activeName == 'menu'" @click="showCloneMenuDialog">克隆</el-button>
      <el-button type="primary" size="mini" v-if="activeName == 'personnel'" @click="showUploadDialog">批量导入</el-button>
      <!-- <el-button type="primary" size="mini">导出</el-button> -->
    </div>

    <!-- 克隆dialog -->
    <el-dialog title="克隆来源" :visible.sync="cloneMenuDialog" width="45%" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
      <el-form ref="cloneForm" :model="cloneModel" label-width="100px" size="small" label-position="right">
        <el-row>
          <el-col>
            <el-form-item label="克隆来源" prop="enterpriseid" :rules="[{ required: true, message: '请选择克隆来源', trigger: '' }]">
              <el-select v-model="cloneModel.enterpriseid" placeholder="请选择">
                <el-option v-for="(item, index) in enterpriseList" :key="index" :label="item.enterpriseShortName" :value="item.key" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancleClone">取 消</el-button>
        <el-button size="small" type="primary" @click="confirmClone">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 批量导入dialog -->
    <el-dialog title="批量导入" :visible.sync="uploadDialog" width="60%" :close-on-click-modal="false" :close-on-press-escape="false">
      <div class="flex-box-start m-b-m align-items-center">
        <p class="left-lable">批量导入</p>
        <el-link :href="`/static/import.xlsx`">下载模板</el-link>
      </div>
      <div class="flex-box-start">
        <p class="left-lable m-t-xs">选择导入文件</p>
        <uploadFile v-if="otherData.enterpriseId" :is-multiple="false" filed-name="file" action="/business/oms/employ/import" :other-data="otherData" :max-size="20" accept-file-type=".xlsx,.xls,.csv" :file-list="fileList" @handleRemove="handleRemove" @handleSuccess="handleSuccess">
          <template v-slot:info>
            <div slot="tip" class="upload__tip m-l-s">支持格式：xls、xlsx、csv，单个文件不能超过20MB</div>
          </template>
        </uploadFile>
      </div>
      <div class="m-t-m">
        <div class="left-lable m-b-s">导入记录</div>
        <div class="record-item" v-for="(item, index) in recordList" :key="index">
          <span>{{ item.createTime | dateFormat('YYYY-MM-DD HH:mm:ss') }}&emsp;{{ item.behaviorDesc }}</span>
          <!-- <el-button class="normal-btn m-r-l" size="text" @click="downloadFile">查看</el-button> -->
        </div>
        <Pagination v-if="total > recordList.length" @change="pageChange" :total="total" />
      </div>
      <!-- <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancleUpload">放弃添加</el-button>
        <el-button size="small" type="primary" @click="confirmUpload">提 交</el-button>
      </span> -->
    </el-dialog>

    <el-dialog title="企业菜单预览" :visible.sync="menuViewDialog" width="60%" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-tree ref="tree" :data="treeMenu" show-checkbox :props="defaultMenuProps" :default-checked-keys="isChoseTree" node-key="primaryKey">
        <span class="custom-tree-node" slot-scope="{ node }">
          <span>{{ node.label }}</span>
        </span>
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="menuViewDialog = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import * as Port from '../../api';
  import { formValid } from '@/lib/utils';
  import tabInfo from './modules/info.vue';
  import tabPersonnel from './modules/personnel.vue';
  import tabMenu from './modules/menu.vue';
  import tabLog from './modules/log.vue';
  import tabStation from './modules/station.vue';
  import tabTag from './modules/tag.vue';
  import tabDimission from './modules/dimission.vue';
  import uploadFile from './modules/upload.vue';
  import { requestTips } from '../../assets/util';

  export default {
    data() {
      return {
        activeName: '',
        uploadDialog: false,
        cloneMenuDialog: false,
        cloneModel: {
          enterpriseid: '', //克隆来源
        },
        cloneList: [
          {
            key: 1,
            value: '哈哈',
          },
        ],
        fileList: [],
        otherData: {},
        recordList: [],
        enterpriseList: [],
        infoData: {},
        currentPage: 1,
        pageSize: 10,
        total: 0,
        menuViewDialog: false,
        treeMenu: [],
        defaultMenuProps: {
          children: 'children',
          label: 'name',
        },
        isChoseTree: [],
      };
    },
    created() {
      // 获取默认的企业key
      if (!this.$route.query.key && localStorage.getItem('userEnterpriseid') && this.$route.query.isAdd != 1) {
        this.$route.query.key = localStorage.getItem('userEnterpriseid')
      }
    },

    async mounted() {
      await this.getTableData();
      await this.initActiveName();
      await this.getData();
      this.tabClick();
    },

    methods: {
      initActiveName() {
        if (this.$verifyPerms('ZEnterpriseInformation')) {
          this.activeName = 'info';
        } else if (this.$verifyPerms('ZOrganizationPosition')) {
          this.activeName = 'station';
        } else if (this.$verifyPerms('ZOrganizationPersonnel')) {
          this.activeName = 'personnel';
        } else if (this.$verifyPerms('ZMenuManagement')) {
          this.activeName = 'menu';
        } else if (this.$verifyPerms('ZOperationLog')) {
          this.activeName = 'operation';
        } else if (this.$verifyPerms('ZLeaveManagement')) {
          this.activeName = 'dimission';
        } else if (this.$verifyPerms('ZSkillManagement')) {
          this.activeName = 'tag';
        }
      },
      //数据源
      async getData() {
        if (this.$route.query.key) {
          let res = await Port.apiEnterpriseInfo(this.$route.query.key);
          this.infoData = res;
          this.otherData = {
            enterpriseId: res.key,
            structureCode: res.structureCode,
          };
        }
      },
      tabClick() {
        if (this.$route.query.key) {
          this.$refs[this.activeName].getInfo('');
        }
      },
      //企业列表
      async getTableData(type) {
        let res = await Port.apiEnterpriseList({
          pageSize: 100,
          currentPage: 1,
        });
        this.enterpriseList = res.rows || [];
      },
      //取消克隆
      cancleClone() {
        this.cloneModel.enterpriseid = '';
        this.cloneMenuDialog = false;
      },
      //确认克隆
      confirmClone() {
        formValid(this, 'cloneForm', this.cloneFn);
      },
      async cloneFn() {
        let res = await Port.apiMenuClone({
          targetEnterpriseId: this.infoData.key,
          ...this.cloneModel,
        });
        requestTips(res, () => {
          this.$refs.menu.getInfo();
          this.cloneMenuDialog = false;
        });
      },
      //取消导入
      cancleUpload() {
        this.uploadDialog = false;
        this.fileList = [];
      },
      //移除文件
      handleRemove(file, fileList) {
        this.fileList.forEach((item, index) => {
          if (item.key == file.key) {
            this.fileList.splice(index, 1);
          }
        });
      },
      //上传成功
      handleSuccess(file, fileList) {
        if (file.data.success) {
          this.fileList.push({
            key: file.data.rows[0].key,
            url: file.data.rows[0].url,
            name: file.data.rows[0].name,
          });
          this.getRecordList();
        } else {
          this.fileList = [];
          this.$message.error(file.data.message);
        }
      },
      //企业详情
      // setInfoData(data){
      //   this.infoData = data
      //   this.otherData = {
      //     enterpriseId:this.infoData.key,
      //     structureCode:this.infoData.structureCode
      //   }
      // },
      showUploadDialog() {
        this.uploadDialog = true;
        this.getRecordList();
      },
      showCloneMenuDialog() {
        this.cloneMenuDialog = true;
      },
      //新增组织
      addGroup() {
        this.$refs.station.addOrganization('');
      },
      //导入记录
      async getRecordList(type) {
        let res = await Port.apiLog({
          pageSize: this.pageSize,
          currentPage: type ? this.currentPage : 1,
          targetType: 'import_employee',
          enterpriseid: this.infoData.key,
        });
        this.recordList = res.rows || [];
      },
      //分页
      pageChange(e) {
        this.currentPage = e.currentPage;
        this.pageSize = e.pageSize;
        this.getRecordList('more');
      },
      showViewMenuDialog() {
        this.getLimitTree();
        this.menuViewDialog = true;
      },
      //右侧权限树
      async getLimitTree() {
        this.isChoseTree = [];
        let res = await Port.apiRoleTree({
          // enterpriseid: this.infoData.key,
          bizId: this.infoData.key,
        });

        if (res.rows.length > 0) {
          this.setCheckedFn(res.rows);
        }

        if (res.rows && res.rows.length) {
          this.treeMenu = res.rows[0].children || [];
        } else {
          this.treeMenu = [];
        }
      },
      setCheckedFn(list) {
        list.forEach(item => {
          item.disabled = true;

          if (item.isUsed && (!item.children || item.children.length == 0)) {
            this.isChoseTree.push(item.primaryKey);
          }
          if (item.children && item.children.length > 0) {
            this.setCheckedFn(item.children);
          }
        });
      },
    },

    components: { tabInfo, tabPersonnel, tabMenu, tabLog, tabStation, tabTag, tabDimission, uploadFile },
  };
</script>
<style lang="scss" scoped>
  .tabs {
    position: relative;
    .btn-box {
      position: absolute;
      top: 20px;
      right: 20px;
    }
    .left-lable {
      width: 120px;
      font-size: 16px;
      font-weight: 550;
    }
    .record-item {
      padding-bottom: 10px;
    }
  }
  ::v-deep .el-tabs__header {
    padding: 15px 25px 0 25px;
  }
</style>
